package Qz54;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 二叉搜索树的第k个结点
 *
 * @author 23737
 * @time 2021.12.12
 */
public class Testr {
    public static void main(String[] args) {
        System.out.println(new Solution().KthNode(new TreeNode(1), 0));
    }
}

class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;
    }
}

class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * @param proot TreeNode类
     * @param k     int整型
     * @return int整型
     */
    public int KthNode(TreeNode proot, int k) {
        // write code here
        if (proot == null) {
            return 0;
        }
        List<Integer> list = new ArrayList<>();
        helper(proot, list);
        Collections.sort(list);
        if(k == 0){
            return list.get(0);
        }
        if(k > list.size()){
            return -1;
        }
        if(list.size() == 1){
            return list.get(0);
        }
        return list.get(k - 1);
    }

    public void helper(TreeNode root, List<Integer> list) {
        if (root == null) {
            return;
        }
        list.add(root.val);
        helper(root.left, list);
        helper(root.right, list);
    }
}
